package zhtt;

import org.hibernate.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.transform.Transformers;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * Created by zhtt on 2017/4/10.
 * 聚合函数
 * 别名
 */
public class JunitTest_alias {

    private Session session;

    @Before
    public void setUp(){
        session=HbnUtil.getSession();
    }

    @Test/** 保证实体类中有个无参构造方法  **/
    public void sql(){
        try{
            session.beginTransaction();
            String sql="select id code ,name username from zhtt0_student";//别名要与实体中的属性相同
            List<StudentAlias> list=session.createSQLQuery(sql)
                    .setResultTransformer(Transformers.aliasToBean(StudentAlias.class)).list();
            for(StudentAlias sa:list){
                System.out.println(sa);
            }
            session.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();;
        }
    }

    @Test
    public void hql(){
        try{
            session.beginTransaction();
            String sql="select new Student(id) from Student";/** 保证有些构造方法 **/
            List<Student> list=session.createQuery(sql).list();
            for(Student sa:list){
                System.out.println(sa);
            }
            session.getTransaction().commit();
        }catch (Exception e){e.printStackTrace();}
    }

    @Test
    public void qbc(){
        try{
            session.beginTransaction();
            ProjectionList projectionList=Projections.projectionList();
            projectionList.add(Projections.property("id"),"code");
            List<StudentAlias> list=session.createCriteria(Student.class)
                    .setProjection(projectionList)
                    .setResultTransformer(Transformers.aliasToBean(StudentAlias.class)).list();
            System.out.println(list);
            session.getTransaction().commit();
        }catch (Exception e){e.printStackTrace();}
    }
}
